package com.eureka.pay.configurer.executor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description: TODO 自定义线程池,处理异步任务。在方法上添加：@Async("asyncTaskExecutor")
 * @Author: 李星 lixing_java@163.com
 * @Date: 2020/2/19 21:18
 */
@Component
@Configuration
public class ThreadPoolTaskExecutorConfig {

    @Bean("asyncTaskExecutor")
    public Executor taskExecutorPool() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 线程名字前缀
        threadPoolTaskExecutor.setThreadNamePrefix("自定义移动支付线程池--");
        // 核心线程数
        threadPoolTaskExecutor.setCorePoolSize(5);
        // 任务队列容量（缓存队列）
        threadPoolTaskExecutor.setQueueCapacity(10);
        // 线程池维护线程的最大数量,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        threadPoolTaskExecutor.setMaxPoolSize(10);
        // 允许空闲时间,当超过了核心线程数之外的线程在空闲时间到达之后会被销毁
        threadPoolTaskExecutor.setKeepAliveSeconds(120);
        // 任务拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy() );
        // 关闭线程池时是否等待当前调度任务完成后才开始关闭
        // 等待
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown( true );
        // 等待时长
        threadPoolTaskExecutor.setAwaitTerminationSeconds( 60 );
        threadPoolTaskExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                // 异常统一处理......发送邮件、发送短信
            }
        });
        //threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}
